import asyncio
from agentscope.agent import AgentBase
from agentscope.message import Msg
import openai

# 设置千问API配置
QWEN_API_KEY = "sk-4e88cf4db3e14894bafaff606d296610"
QWEN_API_BASE = "https://dashscope.aliyuncs.com/compatible-mode/v1"

# 配置OpenAI客户端
client = openai.OpenAI(
    api_key=QWEN_API_KEY,
    base_url=QWEN_API_BASE
)

class QwenAgent(AgentBase):
    def __init__(self, name="千问助手"):
        super().__init__()
        self.name = name  # 设置代理名称

    async def reply(self, msg):
        try:
            # 调用千问API
            response = client.chat.completions.create(
                model="qwen-max",
                messages=[
                    {"role": "system", "content": "你是一个有帮助的AI助手，能够用中文回答用户的问题。"},
                    {"role": "user", "content": msg.content}
                ],
                temperature=0.7,
                max_tokens=1000
            )

            # 提取回复内容
            reply_content = response.choices[0].message.content

            # 返回消息对象
            return Msg(
                name=self.name,
                content=reply_content,
                role="assistant"
            )

        except Exception as e:
            return Msg(
                name=self.name,
                content=f"抱歉，发生错误: {str(e)}",
                role="assistant"
            )

# 创建代理实例
agent = QwenAgent()

# 异步对话循环
async def main():
    print("开始与千问助手对话（输入'退出'结束对话）:")
    while True:
        user_input = input("用户: ")

        if user_input.lower() in ["退出", "exit", "quit"]:
            break

        # 创建用户消息
        user_msg = Msg(
            name="用户",
            content=user_input,
            role="user"
        )

        # 获取回复（使用await）
        response = await agent.reply(user_msg)
        print(f"千问助手: {response.content}")

# 运行异步主函数
if __name__ == "__main__":
    asyncio.run(main())